package com.just.school_campus.service.impl;

import com.just.school_campus.dao.UserMapper;
import com.just.school_campus.model.User;
import com.just.school_campus.model.UserExample;
import com.just.school_campus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userDao;

    @Override
    public User login(String username, String password) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username)
                .andPasswordEqualTo(password)
                .andStatusEqualTo(1);
        List<User> users = userDao.selectByExample(example);
        if(users.size() > 0) {
            return users.get(0);
        }
        else {
            return null;
        }
    }

    @Override
    public int register(User user) {
        synchronized (this){
            while (true){
                    user.setUserId(UUID.randomUUID().toString());
                    //判断是否存在用户名重复
                    UserExample userExample = new UserExample();
                    userExample.createCriteria().andUsernameEqualTo(user.getUsername());
                    List<User> one = userDao.selectByExample(userExample);
                    if(one.size() == 0){
                        int count = userDao.insertSelective(user);
                        if(count == 1){
                            return 1;//返回1表示创建成功
                        }else{
                            return -1;//表示未知错误
                        }
                    }else{
                        return 0;//表示用户名重复
                    }
            }
        }
    }

    @Override
    public User getInfo(String userId) {
        UserExample example = new UserExample();
        example.createCriteria().andUserIdEqualTo(userId);
        User user = userDao.selectByExample(example).get(0);
        return user;
    }

    @Override
    public int setInfo(User user) {
        UserExample example = new UserExample();
        example.createCriteria().andUserIdEqualTo(user.getUserId());
        int count = userDao.updateByExampleSelective(user, example);
        return count;
    }
}
